package com.example.maze.swing;

import com.example.maze.model.Cell;
import com.example.maze.model.Coordinate;
import com.example.maze.model.Maze;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;

/**
 * Swing迷宫显示面板
 * 
 * @author maze-demo
 */
public class MazePanel extends JPanel {
    private static final Logger logger = LoggerFactory.getLogger(MazePanel.class);
    
    // 单元格大小（像素）
    private static final int CELL_SIZE = 20;
    
    // 颜色配置
    private static final Color WALL_COLOR = Color.BLACK;
    private static final Color PATH_COLOR = Color.WHITE;
    private static final Color START_COLOR = Color.GREEN;
    private static final Color END_COLOR = Color.RED;
    private static final Color VISITED_COLOR = new Color(173, 216, 230); // LIGHT_BLUE
    private static final Color SOLUTION_COLOR = Color.YELLOW;
    private static final Color DFS_PATH_COLOR = Color.ORANGE;
    private static final Color BFS_PATH_COLOR = new Color(240, 128, 128); // LIGHT_CORAL
    private static final Color ASTAR_PATH_COLOR = new Color(128, 0, 128); // PURPLE
    private static final Color CURRENT_COLOR = Color.CYAN; // 当前访问的节点
    
    private Maze maze;
    private Map<Coordinate, Color> cellColors;
    private Coordinate highlightCell;
    private Timer highlightTimer;
    
    public MazePanel() {
        this.cellColors = new HashMap<>();
        setBackground(Color.GRAY);
        setPreferredSize(new Dimension(400, 400));
        
        // 添加鼠标监听器用于调试
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (maze != null) {
                    int col = e.getX() / CELL_SIZE;
                    int row = e.getY() / CELL_SIZE;
                    if (row >= 0 && row < maze.getRows() && col >= 0 && col < maze.getCols()) {
                        Cell cell = maze.getCell(row, col);
                        logger.debug("点击单元格: ({},{}) 类型: {}", row, col, cell.getType());
                    }
                }
            }
        });
    }
    
    /**
     * 设置要显示的迷宫
     */
    public void setMaze(Maze maze) {
        this.maze = maze;
        cellColors.clear();
        
        if (maze != null) {
            // 设置面板大小
            int width = maze.getCols() * CELL_SIZE;
            int height = maze.getRows() * CELL_SIZE;
            setPreferredSize(new Dimension(width, height));
            
            // 初始化颜色映射
            initializeCellColors();
            
            logger.debug("设置迷宫显示: {}x{}", maze.getRows(), maze.getCols());
        }
        
        revalidate();
        repaint();
    }
    
    /**
     * 初始化单元格颜色映射
     */
    private void initializeCellColors() {
        for (int row = 0; row < maze.getRows(); row++) {
            for (int col = 0; col < maze.getCols(); col++) {
                Cell cell = maze.getCell(row, col);
                cellColors.put(cell.getCoordinate(), getCellColor(cell.getType()));
            }
        }
    }
    
    /**
     * 获取单元格类型对应的颜色
     */
    private Color getCellColor(Cell.Type cellType) {
        switch (cellType) {
            case WALL:
                return WALL_COLOR;
            case PATH:
                return PATH_COLOR;
            case START:
                return START_COLOR;
            case END:
                return END_COLOR;
            case VISITED:
                return VISITED_COLOR;
            case SOLUTION:
                return SOLUTION_COLOR;
            case DFS_PATH:
                return DFS_PATH_COLOR;
            case BFS_PATH:
                return BFS_PATH_COLOR;
            case ASTAR_PATH:
                return ASTAR_PATH_COLOR;
            default:
                return PATH_COLOR;
        }
    }
    
    /**
     * 更新指定坐标的单元格显示
     */
    public void updateCell(Coordinate coordinate) {
        if (maze == null || coordinate == null) {
            return;
        }
        
        Cell cell = maze.getCell(coordinate);
        Color color = getCellColor(cell.getType());
        cellColors.put(coordinate, color);
        
        // 重绘单元格区域
        int x = coordinate.getCol() * CELL_SIZE;
        int y = coordinate.getRow() * CELL_SIZE;
        repaint(x, y, CELL_SIZE, CELL_SIZE);
    }
    
    /**
     * 高亮显示当前访问的单元格
     */
    public void highlightCurrentCell(Coordinate coordinate) {
        if (coordinate == null) {
            return;
        }
        
        highlightCell = coordinate;
        
        // 重绘高亮单元格
        int x = coordinate.getCol() * CELL_SIZE;
        int y = coordinate.getRow() * CELL_SIZE;
        repaint(x, y, CELL_SIZE, CELL_SIZE);
        
        // 设置定时器500ms后清除高亮
        if (highlightTimer != null) {
            highlightTimer.stop();
        }
        
        highlightTimer = new Timer(500, e -> {
            highlightCell = null;
            repaint(x, y, CELL_SIZE, CELL_SIZE);
        });
        highlightTimer.setRepeats(false);
        highlightTimer.start();
    }
    
    /**
     * 重置迷宫显示到初始状态
     */
    public void resetDisplay() {
        if (maze != null) {
            maze.reset();
            initializeCellColors();
            highlightCell = null;
            repaint();
        }
    }
    
    /**
     * 刷新整个迷宫显示
     */
    public void refresh() {
        if (maze != null) {
            initializeCellColors();
            repaint();
        }
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        if (maze == null) {
            return;
        }
        
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        
        // 绘制所有单元格
        for (int row = 0; row < maze.getRows(); row++) {
            for (int col = 0; col < maze.getCols(); col++) {
                Coordinate coord = new Coordinate(row, col);
                drawCell(g2d, coord);
            }
        }
        
        g2d.dispose();
    }
    
    /**
     * 绘制单个单元格
     */
    private void drawCell(Graphics2D g2d, Coordinate coord) {
        int x = coord.getCol() * CELL_SIZE;
        int y = coord.getRow() * CELL_SIZE;
        
        // 获取单元格颜色
        Color cellColor = cellColors.get(coord);
        if (cellColor == null) {
            Cell cell = maze.getCell(coord);
            cellColor = getCellColor(cell.getType());
            cellColors.put(coord, cellColor);
        }
        
        // 如果是高亮单元格，使用高亮颜色
        if (coord.equals(highlightCell)) {
            cellColor = CURRENT_COLOR;
        }
        
        // 绘制单元格
        g2d.setColor(cellColor);
        g2d.fillRect(x, y, CELL_SIZE, CELL_SIZE);
        
        // 绘制边框
        g2d.setColor(Color.GRAY);
        g2d.drawRect(x, y, CELL_SIZE, CELL_SIZE);
        
        // 为特殊单元格添加额外标记
        Cell cell = maze.getCell(coord);
        if (cell.getType() == Cell.Type.START || cell.getType() == Cell.Type.END) {
            g2d.setColor(Color.BLACK);
            g2d.setStroke(new BasicStroke(2));
            g2d.drawRect(x + 1, y + 1, CELL_SIZE - 2, CELL_SIZE - 2);
        }
    }
    
    /**
     * 获取当前迷宫
     */
    public Maze getMaze() {
        return maze;
    }
}